package com.jingfu.configuration.filter;

import cn.hutool.core.util.StrUtil;
import com.jingfu.common.BadRequestException;
import com.jingfu.common.ErrorCode;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

/**
 * @author jingfuu@163.com
 * @version v1.0
 * @date 2022/1/12 下午5:14
 * AbstractShiroWebFilterConfiguration 会自动收集Filter,无需手工注册到Shiro，只需要声明到容器中
 **/
@Component
public class VerifyCodeFilter extends AccessControlFilter {


    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        //如果是POST提交请求登录时，检查验证码
        if (servletRequest instanceof HttpServletRequest && WebUtils.toHttp(servletRequest).getMethod().equalsIgnoreCase("POST")){
            //校验验证码
            String sessionVertifyCode = (String) SecurityUtils.getSubject().getSession().getAttribute("verifyCode");
            String verifyCode = servletRequest.getParameter("verifyCode");
            if (!StrUtil.equalsIgnoreCase(verifyCode, sessionVertifyCode)) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        //验证码验证失败，存储shiro默认的认证失败错误key
        servletRequest.setAttribute("shiroLoginFailure",ErrorCode.VERTIFY_CODE_ERROR.name());
        return true;
    }
}
